package com.xuehu.cloud.controller;

import com.xuehu.cloud.entities.CommonResult;
import com.xuehu.cloud.entities.Payment;
import com.xuehu.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author guoweia@cslc.com.cn
 * @createTime 2020/11/18 9:14
 * @description
 */
@Slf4j
@RestController
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/pay/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("******插入结果******，result::" + result);
        if(result > 0){
            return new CommonResult(200, "payment添加成功，端口号：" + serverPort + ",result=" + result);
        } else {
            return new CommonResult(444, "payment添加失败，端口号：" + serverPort + ",result=" + result);
        }
    }

    @GetMapping("/pay/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("******查询结果******");
        if(null != payment){
            log.info("******查询成功******，result::" + payment);
            return new CommonResult(200, "payment查询结果，端口号：" + serverPort + ",result=" + payment);
        } else {
            log.info("******查询失败******");
            return new CommonResult(200, "payment查询失败,端口号：" + serverPort, "查询id::" + id);
        }
    }

    @GetMapping("/pay/get/dis")
    public DiscoveryClient queryDiscovery(){
        List<String> services = discoveryClient.getServices();
        for (String info : services) {
            log.info("*****element:" + info + "*****");
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("XUEHU-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances) {
            log.info("***** ServiceId:" + instance.getServiceId() + ",Host:"  + instance.getHost() + ",Uri:" + instance.getUri() + ",Port:" + instance.getPort() + "*****");
        }
        return discoveryClient;
    }

}
